import React, { useState, useEffect } from 'react'
import ControlTitle from '../ControlTitle'
import { Tabs, Spin, Button, Affix, message } from 'antd'
import QuotaLimitItem from '../QuotaLimitItem'
import { udConfigProvider, http } from '@/lib'
import apis from '@/apis/SystemSettings'

const { TabPane } = Tabs

const monthOptions = [
  {
    title: '一月',
    value: 1,
  },
  {
    title: '二月',
    value: 2,
  },
  {
    title: '三月',
    value: 3,
  },
  {
    title: '四月',
    value: 4,
  },
  {
    title: '五月',
    value: 5,
  },
  {
    title: '六月',
    value: 6,
  },
  {
    title: '七月',
    value: 7,
  },
  {
    title: '八月',
    value: 8,
  },
  {
    title: '九月',
    value: 9,
  },
  {
    title: '十月',
    value: 10,
  },
  {
    title: '十一月',
    value: 11,
  },
  {
    title: '十二月',
    value: 12,
  },
]

// 方法组件里面使用useState更新数据会再次执行方法，会重置已保存的变量数据，所以需要将变量定义在方法外
let quotaLimitData = {}
let currentBrand = ''

function QuotaLimitControl(props) {
  const { tabs } = props
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState([])
  const pageContainer = udConfigProvider.ui.getPageContainer()

  useEffect(() => {
    let code = tabs && tabs[0] ? tabs[0].value : undefined
    code && getData(code)
  }, [])

  const getData = (key) => {
    setLoading(true)
    currentBrand = key
    const params = { brandCode: key }
    http.get(apis.QuotaLimitDetail, { params }).then(res => {
      const data = res.data || []
      data.map(item => {
        const { month, ...rest } = item
        if (month) {
          const key = month
          const value = rest
          quotaLimitData[key] = value
        }
      })
      setData(data)
      setLoading(false)
    })
  }

  const getItemData = (field, values) => {
    quotaLimitData[field] = values
  }

  const saveHandle = () => {
    console.log('quotaLimitData', quotaLimitData, currentBrand)
    for (const key in quotaLimitData) {
      if (quotaLimitData.hasOwnProperty(key)) {
        const data = quotaLimitData[key]
        if ((data.monthBeforeNum && !data.multiple) || (!data.monthBeforeNum && data.multiple)) {
          message.error('请补全需要配置月份的数据')
          return
        }
      }
    }
    const brandName = tabs.find(tab => tab.value === currentBrand).title.slice(4, 6)
    const params = Object.keys(quotaLimitData).filter(key=> Object.keys(quotaLimitData[key]).some(item => quotaLimitData[key][item])).map(key => {
      return { ...quotaLimitData[key], brandCode: currentBrand, brandName, month: key }
    })
    setLoading(true)
    http.post(apis.UpdateQuotaLimit, params).then(res => {
      message.success('操作成功')
    }).finally(() => setLoading(false))
  }

  let footer = <div className='detail-footer'><Button type="primary" onClick={saveHandle}>保存</Button></div>
  if (pageContainer) {
    footer = (
      <Affix offsetBottom={0} target={() => pageContainer}>
        {footer}
      </Affix>
    )
  }
  return (
    <>
      <ControlTitle title='计算配额公式配置' desc='用于控制各品牌公司约定配额执行标准上限值控制的规则配置' />
      <Tabs type='card' onChange={getData}>
        {tabs.map(({ value, title }) => {
          return (
            <TabPane tab={title} key={value}>
            <Spin spinning={loading}>
              {monthOptions.map(({title, value}) => {
                const data = quotaLimitData[value]
                return <QuotaLimitItem key={value} title={title} month={value} data={data || {}} transportData={(data) => getItemData(value, data)} />
              })}
            </Spin>
          </TabPane>
          )
        })}
      </Tabs>
      {footer}
    </>
  )
}

export default React.memo(QuotaLimitControl)
